<template>
  <div>
    <button id="add-button" @click="dialogAddFormVisible = true">新增</button>
    <button id="add-button" @click="batchDeleteCategory()">批量删除</button>
    <el-table
      ref="multipleTable"
      :data="categoryData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column type="index" label="序号" width="120"> </el-table-column>
      <el-table-column prop="name" label="分类名称" width="120">
      </el-table-column>
      <el-table-column prop="description" label="分类简介"> </el-table-column>
      <el-table-column prop="no" label="优先级" width="120"> </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="medium"
            style="color: #409eff"
            @click="openEditDialog(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            size="medium"
            style="color: red"
            @click="deleteCategory(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增 -->
    <el-dialog
      title="新增分类信息"
      :visible.sync="dialogAddFormVisible"
      :show-close="false"
    >
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model.trim="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类简介" prop="description">
          <el-input
            v-model.trim="form.description"
            autocomplete="off"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="序号">
          <el-input v-model.number="form.no" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="addCategory()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog
      title="编辑分类信息"
      :visible.sync="dialogEditFormVisible"
      :show-close="false"
    >
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model.trim="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类简介" prop="description">
          <el-input
            v-model.trim="form.description"
            autocomplete="off"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="序号">
          <el-input v-model.number="form.no" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="handleEidt()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getNewsCategory,
  deleteNewsCategory,
  addOrEditNewsCategory,
  batchDeleteNewsCategory
} from '@/api/news'
export default {
  data() {
    return {
      // 分类信息数据
      categoryData: [],
      // 多选的数据
      multipleSelection: [],
      // 新增框是否展示
      dialogAddFormVisible: false,
      dialogEditFormVisible: false,
      // form表单数据
      form: {
        id: '',
        name: '',
        description: '',
        no: ''
      },
      // 校验规则
      rules: {
        name: [{ required: true, message: '分类名称为必填项', trigger: 'blur' }]
      }
    }
  },
  // 监视属性
  watch: {
    // 监视新增框，关闭就清空表单数据
    dialogAddFormVisible: function (value) {
      if (!value) {
        this.clearForm()
      }
    },
    // 监视编辑框，关闭就清空表单数据
    dialogEditFormVisible: function (value) {
      if (!value) {
        this.clearForm()
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 获取分类信息数据
    async getData() {
      this.categoryData = []
      const findAll = await getNewsCategory()
      // 非空判断
      if (findAll) {
        const data = findAll.data
        // this.categoryData.push(...data)
        this.categoryData = data
        this.categoryData.sort((a, b) => a['no'] - b['no'])
      }
    },
    // 根据id删除分类信息
    deleteCategory(categoryInfo) {
      this.$confirm('此操作将永久删除该分类信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const response = await deleteNewsCategory(categoryInfo.id)
          if (response.status === 200) {
            this.getData()
            this.$message({
              type: 'success',
              message: '删除成功'
            })
          } else {
            this.$message.error(response.message)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '操作取消'
          })
        })
    },
    // 新增分类
    async addCategory() {
      if (!this.form.name) {
        this.$refs['form'].validate((valid) => {
          if (!valid) {
            return false
          }
        })
        return
      }
      const response = await addOrEditNewsCategory(this.form)
      if (response.status === 200) {
        this.getData()
        this.clearForm()
        this.$message.success(response.message)
      } else {
        this.$message.error(response.message)
      }
      this.dialogAddFormVisible = false
    },
    // 取消新增，编辑框
    cancel() {
      this.dialogAddFormVisible = false
      this.dialogEditFormVisible = false
      this.$message.info('操作取消')
    },
    // 更新分类信息
    async handleEidt() {
      if (!this.form.name) {
        this.$refs['form'].validate((valid) => {
          if (!valid) {
            return false
          }
        })
        return
      }
      const response = await addOrEditNewsCategory(this.form)
      if (response.status === 200) {
        this.getData()
        this.clearForm()
        this.$message.success(response.message)
      } else {
        this.$message.error(response.message)
      }
      this.dialogEditFormVisible = false
    },
    // 打开编辑
    openEditDialog(categoryInfo) {
      this.dialogEditFormVisible = true
      console.log(this.form)
      // eslint-disable-next-line no-unused-vars
      for (const item in this.form) {
        this.form[item] = categoryInfo[item]
      }
      console.log(this.form)
    },
    // 清空form表单
    clearForm() {
      this.form.id = ''
      this.form.description = ''
      this.form.name = ''
      this.form.no = ''
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 批量删除
    batchDeleteCategory() {
      // 判断是否有信息被选择
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择你要批量删除的分类！')
        return
      }
      this.$confirm('此操作将永久批量删除所选中的分类信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 分类id列表
          const categoryIdList = []
          // 清洗数据，从每行信息中拿到id信息即可
          this.multipleSelection.forEach((item) => {
            categoryIdList.push(item.id)
          })
          const response = await batchDeleteNewsCategory(categoryIdList)
          if (response.status === 200) {
            this.getData()
            this.$message({
              type: 'success',
              message: '删除成功'
            })
          } else {
            this.$message.error(response.message)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '操作取消'
          })
        })
    }
  }
}
</script>

<style scoped lang="scss">
#add-button {
  width: 80px;
  height: 35px;
  margin-right: 10px;
  margin-bottom: 5px;
  font-size: medium;
  font-weight: 700;
  color: #fff;
  background-color: #4c84ee;
  border: none;
  border-radius: 7px;

  &:hover {
    cursor: pointer;
    background-color: #4c85eec6;
    // color: #4c84ee;
  }
}
</style>
